package com.aeye.mbr.upms.client.shiro.session;

import org.apache.shiro.session.mgt.SimpleSession;

import java.util.Map;

/**
 * 重写session
 * Created by shuzheng on 2017/2/27.
 */
public class UpmsSession extends SimpleSession {

    public static enum OnlineStatus {
        on_line("在线"), off_line("离线"), force_logout("强制退出");
        private final String info;

        private OnlineStatus(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }
    }

    // 用户浏览器类型
    private String userAgent;

    // 在线状态
    private OnlineStatus status = OnlineStatus.off_line;

    //上次修改时间，外部调用setAttribute方法时修改该时间字段
    private long lastModifyTime;

    //上次与redis同步时间，与redis服务同步之后修改该字段
    private long lastSyncTime;

    //有属性修改则需求要同步到redis 或者默认60s强制要将本地session同步到redis
    public boolean needSync(){
        return lastModifyTime - lastSyncTime > 0 || System.currentTimeMillis() - lastSyncTime > 1000*60;
    }

    @Override
    public void setAttribute(Object key, Object value) {
        super.setAttribute(key, value);
        lastModifyTime = System.currentTimeMillis();
//        Object oldValue = super.getAttribute(key);
//        if((null == oldValue && null !=value) || (null == value && null !=oldValue)){
//            lastModifyTime = System.currentTimeMillis();
//        }else if(oldValue!=null && value != null && !oldValue.equals(value)){
//            lastModifyTime = System.currentTimeMillis();
//        }
    }

    @Override
    public void setAttributes(Map<Object, Object> attributes) {
        super.setAttributes(attributes);
        lastModifyTime = System.currentTimeMillis();
    }

    public long getLastModifyTime() {
        return lastModifyTime;
    }

    public void setLastModifyTime(long lastModifyTime) {
        this.lastModifyTime = lastModifyTime;
    }

    public long getLastSyncTime() {
        return lastSyncTime;
    }

    public void setLastSyncTime(long lastSyncTime) {
        this.lastSyncTime = lastSyncTime;
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }

    public OnlineStatus getStatus() {
        return status;
    }

    public void setStatus(OnlineStatus status) {
        this.status = status;
    }

}
